import { _decorator, Component, director, resources, instantiate, Node, Label, Button, tween, Vec3, RichText, Prefab, view, Canvas } from 'cc';
import { ExitGame } from './tools/ExitGame';
import { Tag } from './tools/Cons';
import { L } from './tools/L';
const { ccclass, property } = _decorator;

@ccclass('ExitGameDialog')
export class ExitGameDialog extends Component {
    @property(RichText)
    private contentLabel: RichText | null = null;

    @property(Button)
    private confirmBtn: Button | null = null;

    @property(Button)
    private cancelBtn: Button | null = null;

    private static _instance: ExitGameDialog | null = null;
    private static _prefab: Node | null = null;

    // 自动预加载（首次调用show时触发）
    private static async _autoPreload(): Promise<void> {
        if (this._prefab) return;

        return new Promise((resolve, reject) => {
            resources.load("prefabs/ExitGameDialog", (err, prefab) => {
                L.debug(`prefabs/ExitGameDialog 回调, err: ${err}, Prefabs: ${prefab}`);
                if (err) {
                    console.error("ExitGameDialog加载失败:", err);
                    reject(err);
                } else {
                    this._prefab = prefab as unknown as Node;
                    resolve();
                }
            });
        });
    }

    onConfirm(): void {
        this._hideAnimation(() => {
            this.node.destroy();
            ExitGame.inst.exitGame();
        });
    }

    onCancel(): void {
        this._hideAnimation(() => {
            this.node.destroy();
        });
    }

    private _showAnimation(): void {
        this.node.setScale(new Vec3(0.8, 0.8, 1));
        tween(this.node)
            .to(0.2, { scale: new Vec3(1.1, 1.1, 1) })
            .to(0.1, { scale: Vec3.ONE })
            .start();
    }

    private _hideAnimation(callback: () => void): void {
        tween(this.node)
            .to(0.1, { scale: new Vec3(1.1, 1.1, 1) })
            .to(0.2, { scale: new Vec3(0.8, 0.8, 1) })
            .call(() => callback())
            .start();
    }

    public static async show(content: string = "确定要退出游戏吗？"): Promise<void> {
        // 自动触发预加载
        try {
            await this._autoPreload();
        } catch (e) {
            console.error("对话框初始化失败", e);
            return;
        }

        this._instance?.node?.destroy();
        const dialogNode = instantiate(this._prefab);
        director.getScene()?.getComponentInChildren(Canvas)?.node.addChild(dialogNode);
        
        const dialog = dialogNode.getComponent(ExitGameDialog);
        if (dialog && dialog.contentLabel) {
            dialog.contentLabel.string = content;
            dialog._showAnimation();
        }

        this._instance = dialog;
    }
}